package casa.depesos.app.com.utils.html;

import android.graphics.Color;
import android.text.Editable;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;

import org.xml.sax.Attributes;

/**
 * 自定义标签解析类，处理：呵呵呵<span style="{color:#e60012}">哈哈哈</span>嘿嘿嘿
 * Created by Administrator on 2016/3/29.
 */
public class SpanTagHandler implements HtmlTagHandler.TagHandler {

    private String fontColor = "";
    private int color = Color.BLACK;
    private int startIndex = 0;
    private int endIndex = 0;

    @Override
    public void handleTag(boolean open, String tag, Editable output, Attributes attrs) {

        if (tag.toLowerCase().equals("span")) {
            if (open) {
                //开标签，output是空（sax还没读到），attrs有值
                try {
                    for (int i = 0; i < attrs.getLength(); i++) {
                        if (attrs.getLocalName(i).equals("style")) {
                            String style = attrs.getValue(i); //{color:#e60012}
                            if (style.contains("color:")) {
                                int start = style.indexOf("color:");
                                String tmp = style.substring(start + "color:".length());
                                int end = tmp.indexOf(";");
                                tmp = tmp.substring(0, end);
                                fontColor = tmp.trim();
                                if (fontColor.startsWith("rgb")) {
                                    tmp = fontColor.substring("rgb(".length());
                                    end = tmp.indexOf(")");
                                    tmp = tmp.substring(0, end);
                                    String[] ss = tmp.split(",");
                                    color = Color.rgb(Integer.valueOf(ss[0].trim()), Integer.valueOf(ss[1].trim()), Integer.valueOf(ss[2].trim()));
                                }
                            }
                            //    fontColor = style.replace("{", "").replace("}", "").replace("color", "").replace(":", "");
                        }
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                startIndex = output.length();
            } else {
                //闭标签，output有值了，attrs没值
                endIndex = output.length();
                ForegroundColorSpan span;
                try {
                    span = new ForegroundColorSpan(Color.parseColor(fontColor));
                } catch (Throwable e) {
                    span = new ForegroundColorSpan(color);
                }
                try {
                    output.setSpan(span, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }//~~over if
    }
}